package com.meizi.codegenerate.generate.clien.ui.request;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.utils.StringEscapeUtils;
import com.meizi.codegenerate.constant.AnnotationSettingValueConstant;
import com.meizi.codegenerate.constant.CharacteristicConstant;
import com.meizi.codegenerate.constant.JavaClassNameConstant;
import com.meizi.codegenerate.constant.TableNameConstant;
import com.meizi.codegenerate.entity.ColumnsEntity;
import com.meizi.codegenerate.entity.ProjectPositionEntity;
import com.meizi.codegenerate.entity.TablesEntity;
import com.meizi.codegenerate.enums.ColumnDataTypeEnum;
import com.meizi.codegenerate.packagegenerate.PackageGenerate;
import com.meizi.codegenerate.utils.AnnotationUtils;
import com.meizi.codegenerate.utils.AttributeConvertUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author pc
 * @date 2023/7/11 - 10:39 - 星期二
 * @project lambda
 * @package com.meizi.codegenerate.generate.clien.ui.request
 * @by GGbomd猪猪侠
 */
@Slf4j
public class RequestDeleteByIdGenerate {


    /**
     * 获取每个实体的对应的实体主键生生成包装id
     * @param columnsEntity 字段名称
     * @param tableName 表名称
     * @param requesterUrl
     * @param projectPosition
     * @param columnsEntities
     * @param columnsCommentList
     * @throws IOException
     */
    public static void generateDeleteById(ColumnsEntity columnsEntity, String tableName, String requesterUrl,
                                          ProjectPositionEntity projectPosition, List<ColumnsEntity> columnsEntities,
                                          List<ColumnsEntity> columnsCommentList, TablesEntity tablesComment) throws IOException {

        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        //获取requesterBody java类名
        String className = AttributeConvertUtils.tableNameToJava
                (tableName, TableNameConstant.TABLE_PREFIX, true)
                + JavaClassNameConstant.REQUEST_DELETEBY_BYID;
        // 获取完成的文件路径创建文件
        String fullPath = requesterUrl + className + TableNameConstant.JAVA;
        log.info("创建ui下requester路径 fullPath = {}", fullPath);

        CompilationUnit compilationUnit = new CompilationUnit();
        // 添加package
        compilationUnit.setPackageDeclaration(PackageGenerate.requesterPackage(projectPosition));

        // 添加类文件
        ClassOrInterfaceDeclaration declaration = compilationUnit.addClass(className).setPublic(true);
        //添加类级别注释
        declaration.setJavadocComment("@author GG Bond");
        // 添加类级别注解
        declaration.addAnnotation(Data.class);

        map.put(AnnotationSettingValueConstant.CALL_SUPER, AnnotationSettingValueConstant.SET_CALL_SUPER_VALUE);
        declaration.addAnnotation(AnnotationUtils.setAnnotation(EqualsAndHashCode.class, new NodeList<>(),
                map));
        clearMap(map);

        map.put(AnnotationSettingValueConstant.APIMODEL_VALUE, className);
        map.put(AnnotationSettingValueConstant.APIMODEL_DESCRIPTION, tablesComment.getTableComment());
        declaration.addAnnotation(AnnotationUtils.setAnnotation(ApiModel.class, new NodeList<>(),
                map));
        clearMap(map);

        declaration.addField(
                ColumnDataTypeEnum.from(columnsEntity.getType()).getDesc(),
                AttributeConvertUtils.columnNameToJava(columnsEntity.getField(), TableNameConstant.COLUMN_PREFIX, false),
                Modifier.Keyword.PRIVATE
        ).setJavadocComment(StringUtils.isNotBlank(columnsEntity.getColumnComment()) ? columnsEntity.getColumnComment() : "")
                .addAnnotation(AnnotationUtils.setAnnotation(ApiModelProperty.class, new NodeList<>(), map));

        // 是否带有版本号
        List<ColumnsEntity> collect = columnsEntities.stream().filter((x) -> x.getField().equals(CharacteristicConstant.VERSION))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            ColumnsEntity entity = collect.get(0);
            List<ColumnsEntity> columnsEntityList = columnsCommentList.stream()
                    .filter((x) -> x.getField().equals(entity.getField()))
                    .collect(Collectors.toList());
            map.put(AnnotationSettingValueConstant.APIMODELPROPERTY_VALUE, StringEscapeUtils.escapeJava(columnsEntityList.get(0).getColumnComment()));
            declaration.addField(
                            ColumnDataTypeEnum.from(entity.getType()).getDesc(),
                            AttributeConvertUtils.columnNameToJava(entity.getField(), TableNameConstant.COLUMN_PREFIX, false),
                            Modifier.Keyword.PRIVATE
                    ).setJavadocComment(StringUtils.isNotBlank(columnsEntityList.get(0).getColumnComment()) ? columnsEntityList.get(0).getColumnComment() : "")
                    .addAnnotation(AnnotationUtils.setAnnotation(ApiModelProperty.class, new NodeList<>(), map));
        }

        System.out.println(compilationUnit.toString());

        /**
         * 把字符串写入文件
         * 参数1：需要写入的文件，如果文件不存在，将自动创建。  参数2：需要写入的内容
         * 参数3：编码格式     参数4：是否为追加模式（ ture: 追加模式，把字符串追加到原内容后面）
         */
        FileUtils.writeStringToFile(new File(fullPath), compilationUnit.toString(), "UTF-8", false);
    }

    private static void clearMap(Map<String, Object> map) {
        map.clear();
    }
}
